package com.jy.adscm.hcPlan.service.impl;

import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.hcPlan.bean.*;
import com.jy.adscm.hcPlan.bean.develop2.HcPlanBzPackaging;
import com.jy.adscm.hcPlan.bean.develop2.HcPlanJxParsing;
import com.jy.adscm.hcPlan.bean.develop2.HcPlanMjSterilization;
import com.jy.adscm.hcPlan.bean.develop2.HcPlanZjQualitycheck;
import com.jy.adscm.hcPlan.bean.support.HcPlanFinalAssemblyDetail;
import com.jy.adscm.hcPlan.bean.support.HcPlanFinalSupportBean;
import com.jy.adscm.hcPlan.mapper.mysql.*;
import com.jy.adscm.hcPlan.service.HcPlanFinalAssemblyService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.hcPlan.service.HcPlanMakePartExampleService;
import com.jy.adscm.hcPlan.service.HcPlanMakePartMaterielExampleService;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 耗材总装表 服务实现类
 * </p>
 *
 * @author yyy
 * @since 2018-08-13
 */
@Service("hcPlanFinalAssemblyService")
public class HcPlanFinalAssemblyServiceImpl extends ServiceImpl<HcPlanFinalAssemblyMapper, HcPlanFinalAssembly> implements HcPlanFinalAssemblyService {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    HcPlanSaleMapper hcPlanSaleMapper;
    @Autowired
    HcPlanProcedureMapper hcPlanProcedureMapper;
    @Autowired
    HcPlanFinalAssemblyMapper hcPlanFinalAssemblyMapper;
    @Autowired
    HcPlanAfterFinalAssemblyExampleMapper hcPlanAfterFinalAssemblyExampleMapper;
    @Autowired
    HcPlanAfterFinalAssemblyMapper hcPlanAfterFinalAssemblyMapper;
    @Autowired
    HcPlanMakePartExampleService hcPlanMakePartExampleService;
    @Autowired
    HcPlanZzFinalassemblyMapper zzFinalassemblyMapper;
    @Autowired
    HcPlanBzPackagingMapper bzPackagingMapper;
    @Autowired
    HcPlanMjSterilizationMapper mjSterilizationMapper;
    @Autowired
    HcPlanJxParsingMapper jxParsingMapper;
    @Autowired
    HcPlanZjQualitycheckMapper zjQualitycheckMapper;

    @Autowired
    HcPlanMakePartMaterielExampleService hcPlanMakePartMaterielExampleService;

    @Override
    public HcPlanFinalSupportBean queryHcPlanFinalAssemblyListBean() throws AdscmSystemException {

        logger.info("获取所有总装计划...");
        HcPlanFinalSupportBean bean = new HcPlanFinalSupportBean();

//        Map<String,List<HcPlanFinalAssembly>> finalAssemblyMap = new HashMap<>();
        try{
            List<HcPlanFinalAssembly> hcPlanFinalAssemblies = hcPlanFinalAssemblyMapper.queryHcPlanFinalAssemblyList();
            if (hcPlanFinalAssemblies != null && hcPlanFinalAssemblies.size()>0){
                for(int i=0;i<hcPlanFinalAssemblies.size();i++){
                    HcPlanFinalAssembly hpab = hcPlanFinalAssemblies.get(i);
                    if (i == 0){
                        bean.setEndYear(AdscmDateUtils.getTheYear(hpab.getAss_end_date()));
                        bean.setEndMonth(AdscmDateUtils.getTheMonth(hpab.getAss_end_date()));
                    }
                    if (i == hcPlanFinalAssemblies.size() - 1){
                        bean.setStartYear(AdscmDateUtils.getTheYear(hpab.getAss_start_date()));
                        bean.setStartMonth(AdscmDateUtils.getTheMonth(hpab.getAss_start_date()));
                    }

//                    List<String> dates = AdscmDateUtils.getBetweenDate(hpab.getAss_start_date(),hpab.getAss_end_date());
//                    for (String dateKey : dates){
//                        List<HcPlanFinalAssembly> hfList =  finalAssemblyMap.get(dateKey);
//                        if(hfList == null){
//                            hfList = new ArrayList<>();
//                            finalAssemblyMap.put(dateKey,hfList);
//                        }
//                        hfList.add(hpab);
//                    }


                }
            }
            bean.setFinalAssemblyList(hcPlanFinalAssemblies);
//            bean.setFinalAssemblyMap(finalAssemblyMap);

        }catch (Exception e){
            logger.error("获取所有总装计划异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
        return bean;
    }

    @Override
    public List<HcPlanFinalAssembly> queryHcPlanFinalAssemblyList() throws AdscmSystemException {
        logger.info("获取所有总装计划集合...");

        List<HcPlanFinalAssembly> hcPlanFinalAssemblies = null;
        try{
            hcPlanFinalAssemblies = hcPlanFinalAssemblyMapper.queryHcPlanFinalAssemblyList();

        }catch (Exception e){
            logger.error("获取所有总装计划异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
        return hcPlanFinalAssemblies;
    }

    @Override
    public void editFinalAssemblyDate(HcPlanFinalAssembly finalAssembly) throws AdscmSystemException {
        logger.info("直接修改总装的起止时间...");
        try{

            //直接修改总装的起止时间
            //创建商品批号
            HcPlanFinalAssembly assembly = hcPlanFinalAssemblyMapper.selectById(finalAssembly.getId());
            assembly.setAss_start_date(finalAssembly.getAss_start_date());
            assembly.setAss_end_date(finalAssembly.getAss_end_date());
            assembly.setFinal_ass_status(finalAssembly.getFinal_ass_status());
            this.setAssGoodsModel(assembly);

            hcPlanFinalAssemblyMapper.updateById(assembly);

        }catch (Exception e){
            logger.error("直接修改总装的起止时间异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Transactional
    @Override
    public void editAfterFinalAssemblyExample(List<HcPlanAfterFinalAssemblyExample> list) throws AdscmSystemException {
        logger.info("修改某一批次总装后面环节的时间...");
        try{
            if (list != null && list.size()>0){
                for (HcPlanAfterFinalAssemblyExample example:
                     list) {
                    HcPlanFinalAssembly assembly = hcPlanFinalAssemblyMapper.selectById(example.getFinalAssembly());
                    assembly.setFinal_ass_status(1);//修改状态
                    hcPlanFinalAssemblyMapper.updateById(assembly);
                    hcPlanAfterFinalAssemblyExampleMapper.updateById(example);

                    //装配单批次零件制造的数据
                    hcPlanMakePartExampleService.loadHcPartExampleByAssemblyId_new1(assembly.getId());

                    //装配单批次物料采购数据
                    hcPlanMakePartMaterielExampleService.loadHcPartMaterielExampleByAssemblyId(assembly.getId());
                }
            }
        }catch (Exception e){
            logger.error("修改某一批次总装后面环节的时间异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    @Transactional
    @Override
    public void loadFinalAssembly(String date) throws AdscmSystemException {
        logger.info("根据已有销售任务，生成总装数据...");

        try{
            List<HcPlanSale> planSaleList = hcPlanSaleMapper.getAllSalePlan_1(date);
            logger.info("获取所有销售任务【"+(planSaleList != null ? planSaleList.size() : 0 )+"】条");

            //获取总装所有工序的标准时间配置
            Integer ppCycleDay = hcPlanProcedureMapper.getAllCycleDay();
            if (ppCycleDay == null){
                ppCycleDay = 0;
            }
            logger.info("总装所有工序耗费的标准时间：【"+ppCycleDay+"天】");

            if (planSaleList != null && planSaleList.size() > 0){
                for(int i=0;i<planSaleList.size();i++){
                    logger.info("开始装配第：【"+(i+1)+"】条总装数据...");
                    HcPlanSale hps = planSaleList.get(i);

                    Map<String,Object> columnMap = new HashMap<>();
                    columnMap.put("sale_task_flow_num",hps.getSale_task_flow_num());
                    columnMap.put("goods_id",hps.getGoods_id());

                    List<HcPlanFinalAssembly> assemblies = hcPlanFinalAssemblyMapper.selectByMap(columnMap);
                    if (assemblies != null && assemblies.size()>0){
                        continue;
                    }
                    //生成总装数据
                    HcPlanFinalAssembly hpfa = new HcPlanFinalAssembly();
                    hpfa.setSale_task_flow_num(hps.getSale_task_flow_num());
                    hpfa.setAss_cycle_day(ppCycleDay);
                    hpfa.setGoods_id(hps.getGoods_id());//商品id
                    hpfa.setGoods_model(hps.getGoods_model());

                    Date arrivalDate = hps.getPlan_arrived_time();//到货日期

                    Date[] allDate = this.getAssAllDate(arrivalDate,null);
                    hpfa.setAss_start_date(allDate[0]);
                    hpfa.setAss_end_date(allDate[1]);
                    hpfa.setFinal_ass_status(0);//最初状态
                    //保存总装数据
                    hcPlanFinalAssemblyMapper.insert(hpfa);

                    //装配单批次零件制造的数据
//                    hcPlanMakePartExampleService.loadHcPartExampleByAssemblyId(hpfa.getId());

                    //生成单次销售计划耗材总装后的其他计划项目标准配置
                    List<HcPlanAfterFinalAssembly> hcPlanAfterAssembly = hcPlanAfterFinalAssemblyMapper.selectList(null);
                    if (hcPlanAfterAssembly != null && hcPlanAfterAssembly.size()>0){
                        for (HcPlanAfterFinalAssembly hpab : hcPlanAfterAssembly){
                            HcPlanAfterFinalAssemblyExample hpfae = new HcPlanAfterFinalAssemblyExample();
                            hpfae.setFinalAssembly(hpfa.getId());
                            hpfae.setCycleDay(hpab.getCycleDay());
                            hpfae.setProjectName(hpab.getProjectName());
                            HcPlanAfterFinalAssemblyExample hpfae_temp =  hcPlanAfterFinalAssemblyExampleMapper.selectOne(hpfae);
                            if(hpfae_temp != null && hpfae_temp.getId() != null){
                                //更新
                                hpfae.setId(hpfae_temp.getId());
                                hcPlanAfterFinalAssemblyExampleMapper.updateAllColumnById(hpfae);
                            }else {
                                hcPlanAfterFinalAssemblyExampleMapper.insert(hpfae);
                            }
                        }

                    }



                    logger.info("总装所有工序耗费的标准时间：【"+ppCycleDay+"天】");
                }
            }




        }catch (Exception e){
            logger.error("根据已有销售任务，生成总装数据异常",e);
            throw new AdscmSystemException(e.getMessage());
        }

    }

    @Override
    public HcPlanFinalAssemblyDetail getFinalAssemblyDetail(String sale_task_flow_num, String goods_id) throws AdscmSystemException {

        logger.info("获取【"+sale_task_flow_num+"："+goods_id+"】总装详情...");
        HcPlanFinalAssemblyDetail detail = null;
        try {
            Map<String,Object> columnMap = new HashMap<>();
            columnMap.put("sale_task_flow_num",sale_task_flow_num);
            columnMap.put("goods_id",goods_id);

            List<HcPlanFinalAssembly> assemblies = hcPlanFinalAssemblyMapper.selectByMap(columnMap);

            if (assemblies != null && assemblies.size()>0){
                HcPlanFinalAssembly assembly = assemblies.get(0);


                HcPlanSale planSale = hcPlanSaleMapper.getPlanSale(sale_task_flow_num, goods_id);

                detail = (HcPlanFinalAssemblyDetail)planSale;//new HcPlanFinalAssemblyDetail();

                detail.setId(assembly.getId());
                detail.setAss_start_date(assembly.getAss_start_date());
                detail.setAss_end_date(assembly.getAss_end_date());

            }


        }catch (Exception e){
            logger.error("获取【"+sale_task_flow_num+"："+goods_id+"】总装详情异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
        return detail;
    }

    @Override
    public void reEditFinalAssembly(Long finalAssemblyId) throws AdscmSystemException {

        logger.info("重新修改【"+finalAssemblyId+"】总装时间...");
        try {

            HcPlanFinalAssembly assembliy = hcPlanFinalAssemblyMapper.selectById(finalAssemblyId);

            if (assembliy != null){
                int cycleDay = hcPlanAfterFinalAssemblyExampleMapper.getAssemblyExampleCycleDay(finalAssemblyId);
                HcPlanSale planSale = hcPlanSaleMapper.getPlanSale(assembliy.getSale_task_flow_num(), assembliy.getGoods_id());
                Date[] assAllDate = this.getAssAllDate(planSale.getPlan_arrived_time(), cycleDay);
                assembliy.setFinal_ass_status(1);//修改状态
                assembliy.setAss_start_date(assAllDate[0]);
                assembliy.setAss_end_date(assAllDate[1]);

                //创建商品批号
                this.setAssGoodsModel(assembliy);

                //保存总装数据
                hcPlanFinalAssemblyMapper.updateById(assembliy);
            }else {
                throw new AdscmSystemException("没有查询到总装ID为【"+finalAssemblyId+"】的总装数据，修改总装时间失败...");
            }

        }catch (Exception e){
            logger.error("重新修改【"+finalAssemblyId+"】总装时间异常",e);
            throw new AdscmSystemException(e.getMessage());
        }

    }

    private void setAssGoodsModel(HcPlanFinalAssembly assembliy){
        if (AdscmBaseUtils.getInstance().isNotEmpty(assembliy.getAss_end_date(),null)){

            //获取客户信息
            String customerCode = hcPlanSaleMapper.getCustomerCode(assembliy.getSale_task_flow_num());

            String ph = new SimpleDateFormat("yyMMdd").format(assembliy.getAss_end_date());

            if (customerCode.startsWith("XLZ")){
                //兰生的，结尾是G
                ph += "G";
            }else if(customerCode.startsWith("XRS")){
                //蓉生的，结尾是A
                ph += "A";
            }
            assembliy.setGoods_model(ph);
        }

    }


    /**
     * 获取总装的开始和结束时间
     * @param arrivalDate
     * @return
     */
    private Date[] getAssAllDate(Date arrivalDate,Integer faCycleDay){
        //获取总装后的流程的标准时间配置
        if (faCycleDay == null){
            faCycleDay = hcPlanAfterFinalAssemblyMapper.getAllCycleDay();
        }
        if (faCycleDay == null){
            faCycleDay = 0;
        }
        faCycleDay += 1;//要在发货前一天把所有总装后续工作完成，所以这里需要提前一天

        //获取总装所有工序的标准时间配置
        Integer ppCycleDay = hcPlanProcedureMapper.getAllCycleDay();
        if (ppCycleDay == null){
            ppCycleDay = 0;
        }
        if (ppCycleDay > 0 ){
            ppCycleDay -= 1;//总装时间是包含了当天的
        }

        //重新推导这个商品的总装计划
//        Date arrivalDate = goods.getPlanArrivedTime();//hcPlanSale.getArrivalDate();//到货日期
        //总装的结束时间
        Date ppOverDate = AdscmDateUtils.getThatDate(arrivalDate, AdscmBaseUtils.getInstance().getOppositeNum(faCycleDay), Calendar.DATE);

        //总装的开始时间
        Date ppBeginDate = AdscmDateUtils.getThatDate(ppOverDate, AdscmBaseUtils.getInstance().getOppositeNum(ppCycleDay), Calendar.DATE);

        return new Date[]{ppBeginDate,ppOverDate};
    }



    @Override
    public void submitFinalAssemblyTask(Long id) throws AdscmSystemException {
        logger.info("提交总装【"+id+"】任务...");
        try {

           //先修改总装状态
            HcPlanFinalAssembly assembly = hcPlanFinalAssemblyMapper.selectById(id);
            assembly.setFinal_ass_status(2);
            hcPlanFinalAssemblyMapper.updateById(assembly);
            //获取客户信息
            String customerCode = hcPlanSaleMapper.getCustomerCode(assembly.getSale_task_flow_num());


            //总装待办任务
            HcPlanZzFinalassembly zzfa = new HcPlanZzFinalassembly();

            zzfa.setTid(UUID.randomUUID().toString());

            //生成产品批号
            String ph = new SimpleDateFormat("yyMMdd").format(assembly.getAss_end_date());

            zzfa.setBatchnums(ph);

            String typeNums = "";
            if (customerCode.startsWith("XLZ")){
                //兰生的，结尾是G
//                ph += "G";
                typeNums = "G型";
            }else if(customerCode.startsWith("XRS")){
                //蓉生的，结尾是A
//                ph += "A";
                typeNums = "A型";
            }
            //修改销售任务对应的商品信息中的商品型号
            String goods_id = assembly.getGoods_id();

            hcPlanSaleMapper.updateCommodityXh(goods_id,assembly.getGoods_model());
//            hcPlanSaleMapper.updateCommodityXh(goods_id,ph);
            HcPlanSale planSale = hcPlanSaleMapper.getPlanSale(assembly.getSale_task_flow_num(), goods_id);

            zzfa.setTaskcode(Long.parseLong(planSale.getSale_task_flow_num()));
            zzfa.setResourcename(planSale.getGoods_name());
            zzfa.setTypenums(typeNums);
            zzfa.setBusinesstype("总装");
            zzfa.setTaskreleaseperson("f0912aff-1076-4a92-bdd1-652f60e2e757");//文芳
            zzfa.setTaskperformperson("99c303b8-2938-4748-aba4-eb89bfa5ecda");//魏琴
            zzfa.setTaskreleaseaddtime(new Date());
            zzfa.setTaskstartorendtime(assembly.getAss_end_date());
            zzfa.setTasktype(1);
            zzfa.setTasknums(planSale.getGoods_count());
            zzfa.setTaskfinishstate(0);
            zzfa.setTaskstate(0);
            zzfa.setIsreviewtask(0);
            zzfa.setIstaskend(0);
            zzfa.setIstaskstart(0);
            zzfa.setIstaskbegin(0);

            //生成总装待办任务
            zzFinalassemblyMapper.insert(zzfa);

            //生成其他任务
            this.loadOtherTask(zzfa);


        }catch (Exception e){
            logger.error("提交总装【"+id+"】任务异常",e);
            throw new AdscmSystemException(e.getMessage());
        }
    }

    /**
     * 生成其他任务
     */
    private void loadOtherTask(HcPlanZzFinalassembly zzfa){

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssms");
        //包装管理
        HcPlanBzPackaging bz = new HcPlanBzPackaging();
        bz.setTid(UUID.randomUUID().toString());
        bz.setTaskcode(Long.parseLong(format.format(new Date())));
        bz.setBatchnums(zzfa.getBatchnums());
        bz.setResourcename(zzfa.getResourcename());
        bz.setTypenums(zzfa.getTypenums());
        bz.setBusinesstype("包装");
        bz.setTaskreleaseperson("f0912aff-1076-4a92-bdd1-652f60e2e757");
        bz.setTaskreleaseaddtime(new Date());
        bz.setTaskperformperson("a7da2b2d-3e09-4478-b47b-aa850ff132aa");
        bz.setTasktype(1);
        bz.setIstaskstart(0);
        bz.setIstaskbegin(0);
        bz.setTasknums(6141);
        bz.setIstaskend(0);
        bz.setIsreviewtask(0);
        bz.setTaskstate(0);
        bz.setTaskfinishstate(0);

        bzPackagingMapper.insert(bz);
        //
        // 灭菌管理
        HcPlanMjSterilization mj = new HcPlanMjSterilization();
        mj.setTid(UUID.randomUUID().toString());
        mj.setTaskcode(Long.parseLong(format.format(new Date())));
        mj.setBatchnums(zzfa.getBatchnums());
        mj.setResourcename(zzfa.getResourcename());
        mj.setTypenums(zzfa.getTypenums());
        mj.setBusinesstype("灭菌");
        mj.setTaskreleaseperson("f0912aff-1076-4a92-bdd1-652f60e2e757");
        mj.setTaskreleaseaddtime(new Date());
        mj.setTaskperformperson("c06e7827-da19-4a23-9bb2-4ccaf4c37b82");
        mj.setTaskstartorendtime(AdscmDateUtils.getThatDate(zzfa.getTaskstartorendtime(),1,Calendar.DATE));//计划灭菌完成时间【默认为总装的第二天结束】
        mj.setTasktype(1);
        mj.setIstaskstart(0);
        mj.setIstaskbegin(0);
        mj.setTasknums(6141);
        mj.setIstaskend(0);
        mj.setIsreviewtask(0);
        mj.setTaskstate(0);
        mj.setTaskfinishstate(0);
        mjSterilizationMapper.insert(mj);
        //
        // 解析管理
        HcPlanJxParsing jx = new HcPlanJxParsing();
        jx.setTid(UUID.randomUUID().toString());
        jx.setTaskcode(Long.parseLong(format.format(new Date())));
        jx.setBatchnums(zzfa.getBatchnums());
        jx.setResourcename(zzfa.getResourcename());
        jx.setTypenums(zzfa.getTypenums());
        jx.setBusinesstype("解析");
        jx.setTaskreleaseperson("7b1dacfc-eb8d-47a1-a9ef-c127744cfbfd");
        jx.setTaskreleaseaddtime(new Date());
        jx.setTaskperformperson("c06e7827-da19-4a23-9bb2-4ccaf4c37b82");
        jx.setTaskstartorendtime(AdscmDateUtils.getThatDate(mj.getTaskstartorendtime(),1,Calendar.DATE));//计划解析完成时间【默认为灭菌的第二天结束】
        jx.setTasktype(1);
        jx.setIstaskstart(0);
        jx.setIstaskbegin(0);
        jx.setTasknums(6141);
        jx.setIstaskend(0);
        jx.setIsreviewtask(0);
        jx.setTaskstate(0);
        jx.setTaskfinishstate(0);
        jxParsingMapper.insert(jx);
        //
        // 质检管理
        HcPlanZjQualitycheck zj = new HcPlanZjQualitycheck();
        zj.setTid(UUID.randomUUID().toString());
        zj.setTaskcode(Long.parseLong(format.format(new Date())));
        zj.setBatchnums(zzfa.getBatchnums());
        zj.setResourcename(zzfa.getResourcename());
        if (AdscmBaseUtils.getInstance().isNotEmpty(zzfa.getTypenums(),null)){
            zj.setTypenums("JY-FLQ275"+zzfa.getTypenums().substring(0,1));
        }
        zj.setBusinesstype("成品检验");
        zj.setTaskreleaseperson("b285ab00-4aa3-4b28-8ae1-58e8ef12f416");
        zj.setTaskreleaseaddtime(new Date());
        zj.setTaskperformperson("db2044ec-3301-4e83-bbfd-c621a28e3e8d");
//        zj.setTaskstartorendtime(AdscmDateUtils.getThatDate(mj.getTaskstartorendtime(),1,Calendar.DATE));
        zj.setTasktype(1);
        zj.setIstaskstart(0);
        zj.setIstaskbegin(0);
        zj.setTasknums(6141);
        zj.setIstaskend(0);
        zj.setIsreviewtask(0);
        zj.setTaskstate(0);
        zj.setTaskfinishstate(0);
        zjQualitycheckMapper.insert(zj);


    }

}
